<?php

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Argument;
use think\console\input\Option;
use think\facade\App;

class MakeController extends Command
{
    protected function configure()
    {
        $this->setName('make:controller')
            ->addArgument('name', Argument::REQUIRED, '控制器名称')
            ->addOption('extend', null, Option::VALUE_REQUIRED, '继承的父类')
            ->addOption('module', null, Option::VALUE_REQUIRED, '模块名称，默认为 app');
    }

    protected function execute(Input $input, Output $output)
    {
        $name = ucfirst($input->getArgument('name'));
        $extendClass = $input->getOption('extend') ?: 'BaseController';
        $module = $input->getOption('module');

        // 模板路径
        $stubPath = App::getAppPath() . 'command' . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'controller.tpl';

        if (!file_exists($stubPath)) {
            $output->writeln("<error>控制器模板文件不存在</error>");
            return;
        }

        $content = file_get_contents($stubPath);

        // 修改：处理 module 为空的情况
        $namespace = $module ? "app\\{$module}\\controller" : "app\\controller";
        $modelClass = $module ? "app\\{$module}\\model" : "app\\model";
        $validateClass = $module ? "app\\{$module}\\validate" : "app\\validate";

        // 替换变量
        $content = str_replace(
            ['{{className}}', '{{extendClass}}', '{{namespace}}', '{{modelClass}}', '{{validateClass}}'],
            [$name, $extendClass, $namespace, $modelClass, $validateClass],
            $content
        );

        // 写入目标文件
        $controllerPath = app_path() . ($module ? "{$module}/controller/{$name}.php" : "controller/{$name}.php");
        if (!is_dir(dirname($controllerPath))) {
            mkdir(dirname($controllerPath), 0755, true);
        }
        file_put_contents($controllerPath, $content);

        $output->writeln("控制器 {$name} 已生成，继承自 {$extendClass}" . ($module ? "，位于模块 {$module}" : ""));
    }
}